package cn.unknowpupil.sms.utils;

import cn.unknowpupil.common.core.resopnse.ResultResponse;
import cn.unknowpupil.common.core.utils.MapperUtils;
import cn.unknowpupil.sms.configure.AliYunEnum;
import cn.unknowpupil.sms.configure.AliYunSmsConfigure;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created at 2020/10/21 by w10g <br>
 * Initialize AliYunSmsUtil ... <br>
 * 阿里云短信发送工具类
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Slf4j
public class AliYunSmsUtil {


    /**
     * 单独发送短信
     *
     * @param phone
     * @param val          模板值  {"code":"1111"}
     * @param templateCode 模板ID
     * @return
     */
    public static ResultResponse sendSms(String phone, Map val, String templateCode) {
        if (StringUtils.isBlank(phone) || val == null || val.isEmpty()) {
            return ResultResponse.buildFailure("手机号或值不能为空!");
        }
        try {
            return sendSmsToServer(phone, val, templateCode, AliYunSmsConfigure.SingName);
        } catch (Exception e) {
            return ResultResponse.buildFailure("格式转换出错!!!");
        }
    }

    /**
     * 批量发送相同短信内容
     *
     * @param phone {"18523088884","15023102801"}
     * @param val          {"code":"1111"}
     * @param templateCode
     * @return
     */
    public static ResultResponse sendSms(String[] phone, Map val, String templateCode) {
        if (phone == null || phone.length < 1) {
            return ResultResponse.buildFailure("批量手机号不能为空!");
        }
        if (phone.length > 1000) {
            return ResultResponse.buildFailure("批量手机号单次发送最多1000条! 目前手机号条数为:" + phone.length);
        }
        if (val == null || val.isEmpty()) {
            return ResultResponse.buildFailure("短信内容不能为空!");
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : phone) {
            if(StringUtils.isNotBlank(s)){
                stringBuffer.append(s).append(",");
            }

        }
        try {
            return sendSmsToServer(stringBuffer.toString(), val, templateCode, AliYunSmsConfigure.SingName);
        } catch (Exception e) {
            return ResultResponse.buildFailure("格式转换出错。。。");
        }

    }

    /**
     * 发送短信
     * <p>
     * {"Message":"JSON参数不合法","RequestId":"08CFA7F0-3BDA-41EF-9DFD-5745DABC6006","Code":"isv.INVALID_JSON_PARAM"}
     * </p>
     * <p>
     * {"Message":"OK","RequestId":"37F8E3E1-72E5-45AD-8129-A05C376BC757","BizId":"909500568106517856^0","Code":"OK"}
     * </p>
     *
     * @param phone
     * @param map          {"code":"1111"}
     * @param templateCode
     * @param signName
     * @return
     */
    private static ResultResponse sendSmsToServer(String phone, Map map, String templateCode, String signName) throws Exception {
        DefaultProfile profile = DefaultProfile.getProfile("default", AliYunSmsConfigure.AccessKeyID, AliYunSmsConfigure.AccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", MapperUtils.obj2json(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("发送短信返回结果:{}", response.getData());
            Map maps = MapperUtils.json2map(response.getData());
            if ("OK".equals(maps.get("Code").toString())) {
                return ResultResponse.buildSuccess("短信发送成功");
            }
            return ResultResponse.buildFailure(maps.get("Message").toString());

        } catch (ClientException e) {
            log.error("阿里云短信发送错误", e);
            return ResultResponse.buildFailure("短信发送异常!");
        }
    }

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("code","123456");
        String[] phone={"18723981830"};
        ResultResponse resultResponse = sendSms(phone, map, AliYunEnum.BING_PHONE.getValue());
        System.out.println(resultResponse.toString());
    }
}

